package handlers

import (
	"fmt"
	"html/template"
	"net/http"

	"gitee.com/anxu/golang-web/src/models"
	"gitee.com/anxu/golang-web/src/repository"
	"gitee.com/anxu/golang-web/src/service"
)

type hander struct {
}

func (h *hander) redirect(url string, code int, w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, url, code)
}

func (h *hander) user() *models.User {
	id := service.Session.Get("user")

	if id == nil {
		return nil
	}

	if user := repository.User.FindById(id.(int)); user != nil {
		return user
	}
	return nil
}

func (h *hander) render(w http.ResponseWriter, params interface{}, files ...string) {
	var filenames []string

	for _, file := range files {
		filenames = append(filenames, fmt.Sprintf("views/%s.html", file))
	}

	templates := template.Must(template.ParseFiles(filenames...))
	templates.ExecuteTemplate(w, "layout", params)
}

func removeDuplicates(nums []int) int {
	i := 0

	for j := 1; j < len(nums); j++ {
		if nums[i] != nums[j] {
			i++
			nums[i] = nums[j]
		}
	}
	return i
}
